<?php

namespace app\modules\admin\controllers;

use Yii;
use app\Tools\UrlTool;
use app\modules\admin\models\Role;
use app\modules\admin\models\UserRole;
use app\controllers\AdminController;
use app\modules\admin\models\User;

class UserController extends AdminController
{
    public $loginUrl = '/admin/user/login';
    public $adminHomeUrl = '/admin/index/index';

    /**
     * 添加,编辑页面
     */
    public function actionShow()
    {
        $info = [];
        $id = $this->get('id', 0);
        if ($id) {
            $info = User::find()->where(['id' => $id])->one();
        }

        // 已经分配的角色
        $user_role_list = UserRole::find()->where(['uid' => $id])->asArray()->all();
        $related_role_ids = array_column($user_role_list, "role_id");

        $data = [
            'info' => $info,
            'roleList' => Role::getRoleNameList(),  // 所有的角色
            'related_role_ids' => $related_role_ids,    // 已经分配的角色ID
        ];
        return $this->render('set', $data);
    }

    /**
     * 用户编辑,添加
     */
    public function actionSet()
    {
        $id = $this->post('id', 0);
        $name = $this->post('name', '');
        $email = $this->post('email', '');
        $roleIds = $this->post('role_ids', []);

        if (empty($name)) {
            $this->errorJson('用户名不能为空');
        }

        if (empty($email)) {
            $this->errorJson('邮箱不能为空');
        }

        // 邮箱格式已验证
        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $this->errorJson('请输入正确的邮箱格式!');
        }

        $time = time();
        $user_info = User::find()->where(['id' => $id])->one();
        if ($user_info) {
            $user_model = $user_info;
        } else {
            $user_model = new User();
            $user_model->status = 1;
            $user_model->create_at = $time;
        }
        $user_model->name = $name;
        $user_model->email = $email;
        $user_model->update_at = $time;

        if ($user_model->save(0)) {
            // todo 这个地方可以考虑使用事件来实现

            // 已经添加的权限
            $userRoleList = UserRole::find()->where(['uid' => $user_model->id])->asArray()->all();
            $selectRole = array_column($userRoleList, 'role_id');

            // 1:找出要增加的
            $addRoles = array_diff($roleIds, $selectRole);
            if (!empty($addRoles)) {
                foreach ($addRoles as $_role_id) {
                    $userRoleModel = new UserRole();
                    $userRoleModel->uid = $user_model->id;
                    $userRoleModel->role_id = $_role_id;
                    $userRoleModel->create_at = time();
                    $userRoleModel->save(0);
                }
            }

            // 找出删除的 (不在页面选择的角色里面)
            $delRoleIds = array_diff($selectRole, $roleIds);
            if (!empty($delRoleIds)) {
                UserRole::deleteAll(['uid' => $user_model->id, 'role_id' => $delRoleIds]);
            }
        }

        $this->okJson();
    }

    /**
     * 用户列表
     */
    public function actionIndex()
    {
        $user_list = User::find()->asArray()->all();
        User::formatList($user_list);
        // todo 分页
        return $this->render('list', ['list' => $user_list]);
    }

    /**
     * 用户删除
     */
    public function actionDel()
    {
        $id = $this->post('id', '');
        if (!$id) {
            $this->errorJson('参数错误');
        }

        $info = User::find()->where(['id' => $id])->one();
        if (!$info) {
            $this->errorJson('数据不存在');
        }

        $info->status = 0;
        $info->update_at = time();
        $info->save(0);

        $this->jsonOut(1);
    }

    /**
     * 虚拟登录
     * @desc 使用用户ID
     */
    public function actionVlogin()
    {
        $uid = $this->get('uid', '');
        if (!$uid) {
            $this->redirect($this->loginUrl);
        }

        $userInfo = User::find()->where(['id' => $uid])->asArray()->one();
        if (!$userInfo) {
            $this->redirect($this->loginUrl);
        }

        $this->createLoginStatus($userInfo);
        $this->redirect($this->adminHomeUrl);
    }

    /**
     * 用户登录页面
     */
    public function actionLogin()
    {
        return $this->renderPartial('login');
    }

    /**
     * 用户退出
     */
    public function actionLogout()
    {
        $cookie = Yii::$app->response->cookies;
        $cookie->remove($this->cookieToken);
        $this->redirect(UrlTool::createUrl('/admin/user/login'));
    }
}